package com.zvz.sys.controller;

import com.zvz.sys.entity.User;
import com.zvz.sys.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;

@Controller
public class LoginController {
    @Autowired
    private IUserService userService;

    @ResponseBody
    @RequestMapping("sys/login")
    public HashMap<String, Object> login(@RequestParam("username") String username, @RequestParam("password") String password) {
        HashMap<String, Object> r = new HashMap<String, Object>();
        //sha256加密
        password = new Sha256Hash(password).toHex();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (IncorrectCredentialsException ice) {
            r.put("code",-1);
        } catch (UnknownAccountException uae) {
            // 捕获未知用户名异常
            r.put("code",-1);
        } catch (ExcessiveAttemptsException eae) {
            // 捕获错误登录过多的异常
            r.put("code",-1);
        }
        User user = userService.findByUsername(username);
        subject.getSession().setAttribute("user", user);
        r.put("code",0);
        return r;
    }
}